package com.wandian.texas.db.pool;

import java.sql.Connection;
import java.sql.SQLException;

import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
import com.wandian.util.Log;

/**
 * @author long
 * @Create 2012-10-8 上午10:12:10
 * @QQ 108232706
 * @version 1.0
 * @description BoneCPDBPool
 */
public class BoneCPDBPool implements IDBPool
{
	private BoneCP connectionPool = null;
	private BoneCPConfig config;

	public BoneCPDBPool(String poolName, String dbConnUrl, String dbUserName, String dbPassWord, int maxConn, int fallow)
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (Exception e) {
			Log.error("初始化数据库连接池错误", e);
			return;
		}

		this.config = new BoneCPConfig();
		this.config.setJdbcUrl(dbConnUrl);
		this.config.setUsername(dbUserName);
		this.config.setPassword(dbPassWord);

		int minConn = 5;

		this.config.setPartitionCount(fallow);

		this.config.setMinConnectionsPerPartition(minConn);

		this.config.setMaxConnectionsPerPartition(maxConn);

		this.config.setReleaseHelperThreads(3);

		this.config.setStatementsCacheSize(50);

		this.config.setAcquireIncrement(5);

		this.config.setAcquireRetryDelayInMs(3000L);

		this.config.setAcquireRetryAttempts(5);

		this.config.setIdleMaxAgeInMinutes(10L);

		this.config.setTransactionRecoveryEnabled(true);

		this.config.setIdleConnectionTestPeriodInMinutes(10L);

		this.config.setConnectionTimeoutInMs(3000L);
		try
		{
			this.connectionPool = new BoneCP(this.config);
		} catch (Exception e) {
			e.printStackTrace();
			Log.error("初始pool Error", e);
		}
	}

	public void shutdown() {
		if (this.connectionPool != null)
			this.connectionPool.close();
	}

	public String getState()
	{
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("total:" + this.connectionPool.getTotalCreatedConnections()).append(",");
			sb.append("used:" + this.connectionPool.getTotalLeased()).append(",");
			sb.append("free:" + this.connectionPool.getTotalFree());
		} catch (Exception e) {
			Log.error("Pool Error", e);
		}
		return sb.toString();
	}

	public BoneCP getBoneCp() {
		return this.connectionPool;
	}

	public Connection getConnection()
	{
		try
		{
			return this.connectionPool.getConnection();
		} catch (SQLException e) {
			Log.error("获取数据库连接失败", e);
		}
		return null;
	}
}